package com.java.view;
import com.java.model.Student;
import com.java.datamanage.StudentManageSystem;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.Vector;

// 成绩统计面板
class StatsPanel extends JPanel {
    private StudentManageSystem system;
    private JTable statsTable;
    private DefaultTableModel statsTableModel;
    private Collection<String> courses;

    public StatsPanel(StudentManageSystem system) {
        this.system = system;
        initUI();
    }

    private void initUI() {
        setLayout(new BorderLayout());

        // 初始化表格模型
        statsTableModel = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        statsTable = new JTable(statsTableModel);
        JScrollPane scrollPane = new JScrollPane(statsTable);
        add(scrollPane, BorderLayout.CENTER);

        // 刷新数据
        refresh();
    }

    public void refresh() {
        statsTableModel.setRowCount(0);

        // 获取所有课程

        // 更新表头
        Vector<String> columnNames = new Vector<>();
        columnNames.add("学号");
        columnNames.add("姓名");
        columnNames.add("班级");
        columnNames.addAll(courses);
        columnNames.add("成绩");

        statsTableModel.setColumnIdentifiers(columnNames);

        // 填充数据
        DecimalFormat df = new DecimalFormat("#.##");
        for (Student student : system.getAllStudents()) {
            Vector<Object> rowData = new Vector<>();
            //rowData.add(student.getId());
           // rowData.add(student.getName());
            //rowData.add(student.getClassName());

            // 添加课程成绩
            for (String course : courses) {
                Double grade = student.getGradeForCourse(course);
                rowData.add(grade != null ? df.format(grade) : "-");
            }


            statsTableModel.addRow(rowData);
        }
    }
}
